import * as THREE from 'three'
import { stats } from '../stats'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

function createCourse28 (dom: HTMLElement) {
  const scene = new THREE.Scene()

  const camera = new THREE.PerspectiveCamera(75, dom.offsetWidth / dom.offsetHeight, 0.01, 1000)
  camera.position.set(20, 20, 20)

  const render = new THREE.WebGLRenderer()
  render.setSize(dom.offsetWidth, dom.offsetHeight)
  render.shadowMap.enabled = true

  dom.appendChild(render.domElement)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  camera.position.x = -20
  camera.position.y = 20
  camera.position.z = 30
  camera.lookAt(scene.position)
  scene.add(camera)

  const controls = new OrbitControls(camera, render.domElement)
  controls.update()

  createPoints()

  function createPoints () {
    const geom = new THREE.BufferGeometry()
    const material = new THREE.PointsMaterial({
      size: 2,
      vertexColors: true,
      color: 0xffffff,
      map: getTexture()
    })

    material.map!.offset = new THREE.Vector2(0.2, 0)
    material.map!.repeat = new THREE.Vector2(1 / 5, 1)
    material.depthTest = false

    const positions = []
    const colors = []

    for (let x = -30; x < 30; x++) {
      for (let y = -20; y < 20; y++) {
        for (let z = -30; z < 30; z++) {
          positions.push(x * 4, y * 4, z * 40)
          const clr = new THREE.Color(0xffffff)
          colors.push(clr.r, clr.g, clr.b)
        }
      }
    }

    geom.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3))
    geom.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3))

    const cloud = new THREE.Points(geom, material)
    scene.add(cloud)
  }

  function getTexture () {
    const texture = new THREE.TextureLoader().load('https://dongli-three.oss-cn-shanghai.aliyuncs.com/sprite-sheet.png')
    return texture
  }

  render.setAnimationLoop(anmation)

  function anmation () {
    stats.update()
    render.render(scene, camera)
  }

  return { camera, scene, render }
}

export {
  createCourse28
}
